package com.yishuifengxiao.common.security.httpsecurity.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import com.yishuifengxiao.common.security.SecurityProperties;
import com.yishuifengxiao.common.security.httpsecurity.HttpSecurityInterceptor;
import com.yishuifengxiao.common.security.matcher.ExcludeRequestMatcher;
import com.yishuifengxiao.common.social.SocialProperties;

/**
 * <strong>授权资源拦截器</strong><br/>
 * <br/>
 * 
 * 决定系统中哪些资源需要经过授权系统管理<br/>
 * 
 * 这里采用黑名单匹配规则，除了在黑名单里的资源之外其他的资源都要经过授权管理
 *
 * @author yishui
 * @date 2019年10月12日
 * @version 1.0.0
 */
public class AuthorizeResourceInterceptor extends HttpSecurityInterceptor {

	private SecurityProperties securityProperties;

	private SocialProperties socialProperties;

	@Override
	public void configure(HttpSecurity http) throws Exception {
		// 所有的路径都要经过授权
		http.requestMatcher(new ExcludeRequestMatcher(getExcludeUrls()));

	}

	/**
	 * 获取所有不经过oauth2管理的路径
	 *
	 * @return
	 */
	private List<String> getExcludeUrls() {
		// @formatter:off
		List<String> excludeUrls = new ArrayList<>(Arrays.asList("/oauth/**",
				// 登录成功后跳转的地址
				securityProperties.getHandler().getSuc().getRedirectUrl(),
				// QQ登陆的地址
				socialProperties.getFilterProcessesUrl() + "/" + socialProperties.getQq().getProviderId(),
				// 微信登陆的地址
				socialProperties.getFilterProcessesUrl() + "/" + socialProperties.getWeixin().getProviderId(),
				// qq登陆成功后跳转的地址
				socialProperties.getQq().getRegisterUrl(),
				// 微信登陆成功后跳转的地址
				socialProperties.getWeixin().getRegisterUrl(),
				// 登陆页面的URL
				securityProperties.getCore().getLoginPage(),
				// 登陆页面表单提交地址
				securityProperties.getCore().getFormActionUrl(),
				// 退出页面
				securityProperties.getCore().getLoginOutUrl())
				);
		
		//添加上用户自定义配置的路径
		excludeUrls.addAll(this.securityProperties.getExcludeUrls());
		
		// @formatter:on
		return excludeUrls.stream().distinct().collect(Collectors.toList());
	}

	public SecurityProperties getSecurityProperties() {
		return securityProperties;
	}

	public void setSecurityProperties(SecurityProperties securityProperties) {
		this.securityProperties = securityProperties;
	}

	public SocialProperties getSocialProperties() {
		return socialProperties;
	}

	public void setSocialProperties(SocialProperties socialProperties) {
		this.socialProperties = socialProperties;
	}

}
